/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.ensode.jsf.validadora;

import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.component.html.HtmlInputText;
import javax.faces.context.FacesContext;
import javax.faces.validator.FacesValidator;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;


//API de expressões regulares em JAVA
/**
 *
 * @author Rafael
 */
@FacesValidator("emailValidator")
public class EmailValidator implements Validator {

    @Override
    public void validate(FacesContext facesContext, UIComponent uIComponent, Object value) throws ValidatorException {
        Pattern pattern = Pattern.compile("\\w+@\\w+\\.\\w+"); //expressão regular
        Matcher matcher = pattern.matcher((CharSequence) value);
        HtmlInputText htmlImputText = (HtmlInputText) uIComponent;
        String label;

        if (htmlImputText.getLabel() == null || htmlImputText.getLabel().trim().equals("")) {
            label = htmlImputText.getId();
        } else {
            label = htmlImputText.getLabel();
        }

        if (!matcher.matches()) {
            FacesMessage facesMessage = new FacesMessage(label + ": e-mail não válido");
            throw new ValidatorException(facesMessage); //To change body of generated methods, choose Tools | Templates.
        }

    }
}
